package org.pb.basic.service.impl;

import org.pb.basic.mapper.BaseMapper;
import org.pb.basic.query.BaseQuery;
import org.pb.basic.service.IBaseService;
import org.pb.basic.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 基础业务层接口的实现类
 * @author
 * @param <T, R> 业务层接口的泛型 —— 对应表的实体类 和 对应查询类
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class BaseServiceImpl<T, R> implements IBaseService<T, R> {

    @Autowired
    private BaseMapper<T, R> baseMapper;

    @Override
    @Transactional
    public void save(T condition) {
        baseMapper.save(condition);
    }

    @Override
    @Transactional
    public void update(T condition) {
        baseMapper.update(condition);
    }

    @Override
    @Transactional
    public void remove(Long id) {
        baseMapper.remove(id);
    }

    @Override
    public List<T> findAll() {
        return baseMapper.findAll();
    }

    @Override
    public T getById(Long id) {
        return baseMapper.loadById(id);
    }

    @Override
    public PageList<T> findByQuery(R query) {
        if (query == null) {
            throw new RuntimeException("参数不能为空");
        }
        // 获取到分页条数
        Integer count = baseMapper.countQuery(query);
        // 如果总记录条数为0或者记录记录条数为空，则表示分页查询失败
        if (count == null || count <= 0) {
            throw new RuntimeException("查询失败");
        }
        // 获取到分页查询数据
        List<T> list = baseMapper.findByQuery(query);
        // 如果departments为空，则证明查询不到记录，则查询失败，直接返回一个空的集合
        if (list == null) {
            return new PageList<>();
        }
        // 将分页查询数据赋值到PageList中
        PageList<T> pageList = new PageList<>();
        pageList.setData(list);
        pageList.setTotals(count);
        return pageList;
    }

    @Override
    public void batchRemove(List<Long> ids) {
        if (ids == null) {
            return;
        }
        baseMapper.batchRemove(ids);
    }
}
